<template>
  <a-spin :spinning="confirmLoading">
    <ants-form-container :disabled="formDisabled">
      <a-form slot="detail" :form="form">
        <a-row>
          <!--          <a-col :span="24">-->
          <!--            <a-form-item label="是否有封面" :label-col="labelCol2" :wrapper-col="wrapperCol2">-->
          <!--              <ants-dict-select-tag-->
          <!--                v-decorator="['isCover', validatorRules.isCover]"-->
          <!--                type="radioButton"-->
          <!--                :trigger-change="true"-->
          <!--                dict-code="yn"-->
          <!--                placeholder="请选择发布形式"-->
          <!--                @change="showCover"-->
          <!--              />-->
          <!--            </a-form-item>-->
          <!--          </a-col>-->
          <a-col :span="24">
            <a-form-item label="封面" :label-col="labelCol2" :wrapper-col="wrapperCol2">
              <span style="color: red">只能上传1张封面照片！！！</span>
              <ants-image-upload
                biz-path="article-cover"
                v-decorator="['cover',  validatorRules.cover]"
              />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="摘要" :label-col="labelCol2" :wrapper-col="wrapperCol2">
              <a-textarea
                v-decorator="['abstractText', validatorRules.abstractText]"
                :rows="4"
                show-count
                :maxLength="200"
                placeholder="请输入摘要，最大200个字！支持一件提取正文前200字符！"
              />
              <a-button shape="round" size="small" @click="extractText()">一件提取</a-button>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="分类" :label-col="labelCol2" :wrapper-col="wrapperCol2">
              <ul class="wallpaper-type-list">
                <template v-for="item in sortTags">
                  <li
                    class="item animated swing"
                    :class="sortCurrent === item.key ?'active' : ''"
                    @click="selectSortCurrent(item.key)"
                  >
                    {{ item.label }}
                  </li>
                </template>
              </ul>
              <!--              <a-input v-decorator="['articleSort_', validatorRules.articleSort]" v-show="false"/>-->
              <div style="color: #f5222d" v-show="isArticleSort">请选择分类!</div>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="标签" :label-col="labelCol2" :wrapper-col="wrapperCol2">
              <div class="lable-div">
                <div class="button-content">我的标签</div>
                <ul class="wallpaper-type-list">
                  <template v-for="tag in myLableTags">
                    <li
                      class="item animated swing"
                      :class="initClass(tag.key)  ?'active' : ''"
                      @click="selectedTags.length == 0 ? selectTagChange(tag.key, true) : selectedTags.indexOf(tag.key) > -1  ? selectTagChange(tag.key, false) : selectTagChange(tag.key, true)"
                    >
                      {{ tag.label }}
                    </li>
                  </template>
                  <li
                    v-if="myLableTags.length < 5"
                    class="item animated swing"
                    @click="customLabel"
                  >
                    + 自定义标签
                  </li>
                </ul>
                <div class="button-content">其他标签</div>
                <ul class="wallpaper-type-list">
                  <template v-for="tag in lableTagAll">
                    <li
                      class="item animated swing"
                      :class="selectedTags.indexOf(tag.key) > -1  ?'active' : ''"
                      @click="selectedTags.length == 0 ? selectTagChange(tag.key, true) : selectedTags.indexOf(tag.key) > -1  ? selectTagChange(tag.key, false) : selectTagChange(tag.key, true)"
                    >
                      {{ tag.label }}
                    </li>
                  </template>
                </ul>
              </div>
              <div style="color: #f5222d" v-show="isArticleLable">请选择分类!</div>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="文章类型" :label-col="labelCol2" :wrapper-col="wrapperCol2">
              <ants-dict-select-tag
                v-decorator="['articleType', validatorRules.articleType]"
                type="radioButton"
                :trigger-change="true"
                dict-code="article_type"
                placeholder="请选择文章类型"
                @change="articleTypeChange"
              />
            </a-form-item>
          </a-col>
          <div v-show="isAuthorizationShow">
            <a-col :span="24">
              <a-form-item label="原文链接" :label-col="labelCol2" :wrapper-col="wrapperCol2">
                <a-input
                  v-decorator="['originalTextLink', { rules: [{ required: originalTextLink, message: '请输入原文链接' }] }]"
                  placeholder="请输入原文链接"
                />
              </a-form-item>
            </a-col>
            <a-col :span="24">
              <a-form-item label="允许转载/翻译" :label-col="labelCol2" :wrapper-col="wrapperCol2">
                <ants-checkbox
                  v-decorator="['isAuthorAuthorization', { rules: [{ required: isAuthorAuthorization, message: '请确认允许转载/翻译' }] }]"
                  :options="sportOptions"
                />
                <span style="margin-left: 10px; color: red">{{ tips }}</span>
              </a-form-item>
            </a-col>
          </div>
          <a-col :span="24">
            <a-form-item label="发布形式" :label-col="labelCol2" :wrapper-col="wrapperCol2">
              <ants-dict-select-tag
                v-decorator="['publishForm', validatorRules.publishForm]"
                type="radioButton"
                :trigger-change="true"
                dict-code="publish_form"
                placeholder="请选择发布形式"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </ants-form-container>
    <article-lable-form-sub ref="articleLableFormSub" @ok="customLabelOk"/>
  </a-spin>
</template>

<script>
import AntsFormContainer from '@/components/ants/AntsFormContainer'
import AntsImageUpload from '@/components/ants/AntsImageUpload'
import AntsCheckbox from '@/components/ants/AntsCheckbox'
import pick from 'lodash.pick'
import AntsSearchSelectTag from '@/components/dict/AntsSearchSelectTag'
import AntsDictSelectTag from '@/components/dict/AntsDictSelectTag'
import {getAction, httpAction} from '@/api/manage'
import ArticleLableModal from '../subTables/ArticleLableModal'
import ArticleSortModal from '../subTables/ArticleSortModal'
import ArticleLableFormSub from '../subTables/ArticleLableFormSub'
import {ellipsis} from "@/utils/util";

export default {
  name: 'PublishForm',
  components: {
    AntsImageUpload,
    AntsFormContainer,
    AntsSearchSelectTag,
    AntsDictSelectTag,
    AntsCheckbox,
    ArticleLableModal,
    ArticleSortModal,
    ArticleLableFormSub
  },
  props: {
    // 流程表单data
    formData: {
      type: Object,
      default: () => {
      },
      required: false
    },
    // 表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    // 表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    },
    articleTitle: {
      type: String,
      default: '',
      required: true
    },
    articleContentMd: {
      type: String,
      default: '',
      required: true
    },
    articleContentHtml: {
      type: String,
      default: '',
      required: true
    },
    targetPath: {
      type: String,
      default: '',
      required: true
    }
  },
  data() {
    return {
      form: this.$form.createForm(this),
      fileNum: 4,
      model: {},
      labelCol: {
        xs: {span: 24},
        sm: {span: 6}
      },
      wrapperCol: {
        xs: {span: 24},
        sm: {span: 16}
      },
      labelCol2: {
        xs: {span: 24},
        sm: {span: 3}
      },
      wrapperCol2: {
        xs: {span: 24},
        sm: {span: 20}
      },
      sportOptions: [
        {
          value: '1'
        }
      ],
      validatorRules: {
        isCover: {
          rules: [
            {required: true, message: '请选择是否有封面!'}
          ]
        },
        abstractText: {
          rules: [
            {required: true, message: '请输入摘要，最大200个字！支持一件提取正文前200字符！'}
          ]
        },
        cover: {
          rules: [
            {required: true, message: '请上传封面!'}
          ]
        },
        articleSort: {
          rules: [
            {required: true, message: '请选择分类!'}
          ]
        },
        articleLable: {
          rules: [
            {required: true, message: '请选择标签!'}
          ]
        },
        articleType: {
          rules: [
            {required: true, message: '请选择文章类型!'}
          ]
        },
        publishForm: {
          rules: [
            {required: true, message: '请选择发布形式!'}
          ]
        }
      },
      url: {
        add: '/article/add',
        edit: '/article/edit',
        getById: '/article/getById',
        getLableById: '/articleLable/getLableById',
        getSortByIds: '/articleSort/getSortByIds',
        genArticleLableList: '/articleLable/genArticleLableList',
        getLableAll: '/articleLable/getLableAll',
        genArticSortList: '/articleSort/genArticSortList'
      },
      confirmLoading: false,
      originalTextLink: false, // 原文链接 是否必填
      isAuthorAuthorization: false, // 允许转载/翻译 是否必填
      isAuthorizationShow: false,
      tips: '',
      width: 500,
      height: 300,
      myLableTags: [],
      lableTagAll: [],
      sortTags: [],
      cover: false, // 封面 是否必填
      sortCurrent: '',
      selectedTags: [],
      isArticleSort: false,
      isArticleLable: false,
      // 发布状态；1：已发布；2：定时发布；3：草稿；
      publishState: '1',
      publishNowFlag: false,
      quartzPushDate: null,
      quartzPushTime: null
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    }
  },
  created() {
    this.getArticleLable()
    this.genArticSortList()
  },
  methods: {
    getArticleLable() {
      getAction(this.url.genArticleLableList, {}).then((res) => {
        if (res.success) {
          this.myLableTags = res.result
        }
      })
      getAction(this.url.getLableAll, {}).then((res) => {
        if (res.success) {
          this.lableTagAll = res.result
        }
      })
    },
    genArticSortList() {
      getAction(this.url.genArticSortList, {}).then((res) => {
        if (res.success) {
          this.sortTags = res.result
        }
      })
    },
    add(articleData) {
      this.edit(articleData)
    },
    async edit(record) {
      if (record.id) {
        await getAction(this.url.getById, {
          'id': record.id
        }).then((res) => {
          if (res.success) {
            record = res.result
          }
        })
      }
      if (record.articleSort) {
        this.sortCurrent = record.articleSort
      }
      if (record.articleLable) {
        await getAction(this.url.getLableById, {
          'ids': record.articleLable
        }).then((res) => {
          if (res.success) {
            res.result.forEach(tag => {
              this.selectedTags.push(tag.key)
            })
          }
        })
      }
      this.authorizationShow(record.articleType)
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        this.form.setFieldsValue(pick(this.model, 'isCover', 'cover', 'abstractText', 'articleType', 'publishForm', 'originalTextLink', 'isAuthorAuthorization'))
      })
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {

          const formData = Object.assign(this.model, values)
          var url = ''
          var method = ''
          if (!this.model.id) {
            url = that.url.add
            method = 'post'
          } else {
            url = that.url.edit
            method = 'put'
          }
          formData.publishState = this.publishState
          formData.publishNowFlag = this.publishNowFlag
          if (this.publishState === '2') {
            formData.quartzPushDate = this.quartzPushDate
            formData.quartzPushTime = this.quartzPushTime
          }
          formData.title = this.articleTitle
          formData.content = this.articleContentMd
          formData.html = this.articleContentHtml
          if (!this.sortCurrent) {
            this.isArticleSort = true
            return
          }
          if (this.selectedTags.length == 0) {
            this.isArticleLable = true
            return
          }
          that.confirmLoading = true
          formData.articleSort = this.sortCurrent
          formData.articleLable = this.selectedTags.join(',')
          httpAction(url, method, formData).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              if (that.targetPath) {
                this.$router.push({
                  path: '/' + that.targetPath
                })
              } else {
                this.$router.push({
                  path: '/article/articleList'
                })
              }
            } else {
              that.$message.warning(res.message)
              that.$emit('errorPush')
            }
          }).finally(() => {
            that.confirmLoading = false
            that.$emit('errorPush')
          })
        } else {
          that.$emit('errorPush')
        }
      })
    },
    articleTypeChange(e) {
      this.authorizationShow(e.target.value)
    },
    authorizationShow(value) {
      if (value === '1') {
        this.isAuthorizationShow = false
        this.originalTextLink = false
        this.isAuthorAuthorization = false
        this.tips = ''
      } else if (value === '2') {
        this.isAuthorizationShow = true
        this.originalTextLink = true
        this.isAuthorAuthorization = true
        this.tips = '原文允许转载/本次转载获得作者授权。转载文章不能设置VIP可见。'
      } else if (value === '3') {
        this.isAuthorizationShow = true
        this.originalTextLink = true
        this.isAuthorAuthorization = true
        this.tips = '原文允许翻译/本次翻译获得作者授权，翻译文章尽量填写原文链接。'
      }
    },
    showCover(e) {
      if (e.target.value === '1') {
        this.cover = true
      } else {
        this.cover = false
      }
    },
    selectTagChange(tag, checked) {

      const {selectedTags} = this
      const nextSelectedTags = checked
        ? [...selectedTags, tag]
        : selectedTags.filter(t => t !== tag)
      if (nextSelectedTags.length <= 5) {
        this.selectedTags = nextSelectedTags
      } else {
        this.$message.error('每篇文章只能选择5个标签！')
      }
      if (this.selectedTags.length > 0) {
        this.isArticleLable = false
      } else {
        this.isArticleLable = true
      }
    },
    selectSortCurrent(key) {
      this.isArticleSort = false
      this.sortCurrent = key
    },
    initClass(tag) {
      return this.selectedTags.indexOf(tag) > -1
    },
    customLabel() {
      this.$refs.articleLableFormSub.add()
    },
    customLabelOk() {
      this.getArticleLable()
    },
    extractText() {
      let abstractText = ellipsis(this.articleContentHtml.replace(/(<([^>]+)>)/ig, ''), 200)
      this.$nextTick(() => {
        this.form.setFieldsValue({ abstractText: abstractText })
      })
    }
  }
}
</script>

<style scoped>
.lable-div {
  border: 1px solid rgba(158, 158, 158, 0.22);
  height: 300px;
  margin-right: 10px;
  margin-top: 10px;
  padding: 10px;
  overflow-y: auto;
  border-radius: 4px;
  box-shadow: 2px 2px 20px 5px rgba(158, 158, 158, 0.2);
}


.wallpaper-type-list {
  display: grid;
  gap: 15px;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  border-top: 1px solid #ebeef5;
  padding-top: 15px;
}

.item {
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  background: #f2f6fc;
  height: 28px;
  line-height: 28px;
  border-radius: 14px;
  cursor: pointer;
  color: #606266;
  font-size: 12px;
  padding: 0 15px;
  text-align: center;
  transition: color 0.35s, background 0.35s, box-shadow 0.35s, -webkit-transform 0.35s;
  transition: color 0.35s, background 0.35s, box-shadow 0.35s, transform 0.35s;
  transition: color 0.35s, background 0.35s, box-shadow 0.35s, transform 0.35s, -webkit-transform 0.35s;
}

.animated {
  -webkit-animation-duration: 1s;
  animation-duration: 1s;
  -webkit-animation-fill-mode: both;
  animation-fill-mode: both;
}

.swing {
  -webkit-transform-origin: top center;
  transform-origin: top center;
  -webkit-animation-name: swing;
  animation-name: swing;
}

li {
  list-style: none;
}

.item:hover {
  -webkit-transform: translateY(-2px);
  transform: translateY(-2px);
  box-shadow: 0 5px 5px rgb(0 0 0 / 10%);
}

.active {
  -webkit-transform: translateY(-2px);
  transform: translateY(-2px);
  color: #fff;
  background: #409eff;
  box-shadow: 0 5px 5px rgb(0 0 0 / 10%);
}

ul {
  list-style: none;
  margin: 0;
  padding: 0 30px
}

.button-content {
  font-weight: 700;
}
</style>
